﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bouyei.DbFactory.DbSqlProvider.SqlKeywords
{
    public class Values : WordsBase
    {
        public Values() : base(AttributeType.IgnoreWrite | AttributeType.Ignore)
        {

        }

        public string ToString(Dictionary<string, object> columns)
        {
            List<string> array = new List<string>(columns.Count);

            foreach (KeyValuePair<string, object> kv in columns)
            {
                array.Add(ObjectValueFormat(kv.Value));
            }

            return $"({string.Join(",", columns.Select(x => x.Key))}) Values (" + string.Join(",", array) + ") ";
        }
    }

    public class Values<T> : WordsBase
    {
        public MappingOption option { get; private set; }

        public Values(MappingOption option = MappingOption.None)
            : base(typeof(T), AttributeType.IgnoreWrite | AttributeType.Ignore)
        {
            this.option = option;
        }

        /// <summary>
        /// 列匹配默认使用第一个项，如果有多项值并忽略空值建议保证空值一致
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string ToString(params T[] value)
        {
            StringBuilder builder = new StringBuilder();
            var pros = GetProperties().ToArray();

            for (int i = 0; i < value.Length; ++i)
            {
                var colValues = base.ParameterFormat(pros, value[i], option);
                if (i == 0)
                {
                    builder.AppendFormat("({0}) Values ", string.Join(",", colValues.columns));
                }

                builder.AppendFormat("({0}){1}", colValues.values, i < value.Length - 1 ? "," : "");
            }
            return builder.Append(" ").ToString();
        }

        public string ToString(Dictionary<string, object> columns)
        {
            List<string> array = new List<string>(columns.Count);
            foreach (KeyValuePair<string, object> kv in columns)
            {
                array.Add(ObjectValueFormat(kv.Value));
            }

            return $"({string.Join(",", columns.Select(x => x.Key))}) Values (" + string.Join(",", array) + ") ";
        }

        public string ToString<R>(Func<T, R> selector)
        {
            var columns = GetColumnsKeyValue(selector, option);
            var val = columns.Select(x => x.Value);
            var col = columns.Select(x => x.Key);
            return $"({string.Join(",", col)}) Values (" + string.Join(",", val) + ") ";
        }
    }
}
